//
//  SZLSingleDetailViewController.m
//  Shengzhuli
//
//  Created by 卡忙科技 on 16/8/26.
//  Copyright © 2016年 kamangkeji. All rights reserved.
//

#import "SZLSingleDetailViewController.h"
#import "SingleListNetWork.h"
#import "SZLAccountHelper.h"
#import "AddressField.h"
#import "SingleListTableViewCell.h"
#import <UIImageView+WebCache.h>
#import "SingleActionNetWork.h"
#import "SZLSinglePayViewController.h"
#import "MBProgressHUD+MJ.h"
#import "UIAlertView+Entension.h"
#import "SingleActionTool.h"
#import "StarSlider.h"
#import "UIAlertView+Entension.h"

@interface SZLSingleDetailViewController ()<UIScrollViewDelegate,UITextViewDelegate>
{
    BOOL isAnimate;//是否是键盘引起的scrollview滚动
    BOOL isTextView;//是否是textview弹出的键盘
}

@property (weak, nonatomic) IBOutlet UIScrollView *scrollview;
@property (weak, nonatomic) IBOutlet UIView *containView;
@property (weak, nonatomic) IBOutlet UILabel *singleLab;
@property (weak, nonatomic) IBOutlet UIButton *statusBtn;
@property (weak, nonatomic) IBOutlet UIView *addressView;
@property (weak, nonatomic) IBOutlet UILabel *nameLab;
@property (weak, nonatomic) IBOutlet UILabel *tellLab;
@property (weak, nonatomic) IBOutlet UILabel *addressLab;
@property (weak, nonatomic) IBOutlet UIView *pickSelfView;
@property (weak, nonatomic) IBOutlet UIView *riseView;
@property (weak, nonatomic) IBOutlet UILabel *riseLab;
@property (weak, nonatomic) IBOutlet UIView *goodsView;
@property (weak, nonatomic) IBOutlet UIImageView *iconImageView;
@property (weak, nonatomic) IBOutlet UILabel *goodsNameLab;
@property (weak, nonatomic) IBOutlet UILabel *priceLab;
@property (weak, nonatomic) IBOutlet UILabel *freightLab;
@property (weak, nonatomic) IBOutlet UILabel *countLab;
@property (weak, nonatomic) IBOutlet UILabel *totalMoneyLab;
@property (weak, nonatomic) IBOutlet UILabel *singleStatusLab;

@property (weak, nonatomic) IBOutlet UIView *expressView;
@property (weak, nonatomic) IBOutlet UILabel *expressLab;
@property (weak, nonatomic) IBOutlet UILabel *expressNumLab;
@property (weak, nonatomic) IBOutlet UIView *commentView;
@property (weak, nonatomic) IBOutlet UIView *starView;
@property (weak, nonatomic) IBOutlet AddressField *commentTextView;
@property (weak, nonatomic) IBOutlet UIButton *sureBtn;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *containViewHeightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *addressViewHeightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *pickSelfViewHeightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *riseViewHeightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *expressViewHeightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *commentViewHeightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollViewBottomConstraint;

@property (nonatomic,strong) SingleListModel *model;
@property (nonatomic,assign) CGFloat originHeight;
@property (nonatomic,weak) StarSlider *slider;
@property (nonatomic,assign) NSInteger starCount;

@end

@implementation SZLSingleDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"订单详情";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.scrollview.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
    [self setView];
    //xib页面 指示器会偏移  self.view的bounds不对是600
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self getSingleDetail];
    });
    [self addObserve];
}
- (void)setView
{
    self.statusBtn.layer.borderColor = [UIColor redColor].CGColor;
    self.addressView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.pickSelfView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.goodsView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.commentTextView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.commentTextView.placeHolder = @"请输入评价内容";
    self.containViewHeightConstraint.constant = CGRectGetMaxY(self.sureBtn.frame)+20-(ScreenH-64);
    self.originHeight = CGRectGetMaxY(self.sureBtn.frame)+20;
    StarSlider *slider = [[StarSlider alloc]initWithFrame:CGRectMake(0, 0, 170, 30)];
    self.slider = slider;
    slider.valueBlock = ^(NSInteger count){
        self.starCount = count;
    };
    [self.starView addSubview:slider];
}
- (IBAction)sureClick:(UIButton *)btn
{
    if (self.starCount<1) {
        [MBProgressHUD showError:@"请选择评星" toView:self.view];
        return;
    }
    if (self.commentTextView.text.length<1) {
        [MBProgressHUD showError:@"请填写评论内容" toView:self.view];
        return;
    }
    [self commitContent];
}
- (void)setValue
{
    self.singleLab.text = self.model.orderNo;
    if (self.model.isUserselfPick) {
        self.addressViewHeightConstraint.constant = 0.001;
    }else{
        self.nameLab.text = self.model.receivePerson;
        self.tellLab.text = self.model.receivePersonPhone;
        self.addressLab.text = self.model.receiveAddress;
        self.pickSelfViewHeightConstraint.constant = 0.001;
    }
    if (!self.model.isNeedInvoice) {
        self.riseViewHeightConstraint.constant = 0.001;
    }else{
        self.riseLab.text = self.model.invoiceTitle;
    }
    [self.iconImageView sd_setImageWithURL:[NSURL URLWithString:self.model.thumbnailUrl] placeholderImage:GetImage(@"default_goods_image")];
    self.goodsNameLab.text = self.model.productName;
    self.priceLab.text = [NSString stringWithFormat:@"¥%.2f",self.model.productUnitPrice];
    self.totalMoneyLab.text = [NSString stringWithFormat:@"¥%.2f",self.model.totalPrice];
    self.freightLab.text = [NSString stringWithFormat:@"¥%.2f",self.model.freight];
    self.countLab.text = [NSString stringWithFormat:@"x %zd",self.model.productCount];
    
    if (self.model.status == SingleTypeStatusUnpay) {//商家看不到
        self.singleStatusLab.text = @"待付款";
        self.statusBtn.tag = ActionTypeToPay;
        self.expressViewHeightConstraint.constant = 0.001;
        self.commentViewHeightConstraint.constant = 0.001;
        self.sureBtn.hidden = YES;
        self.statusBtn.tag = ActionTypeToPay;
    }else if (self.model.status == SingleTypeStatusAlreadyPay){//商家显示发货
        self.singleStatusLab.text = @"待发货";
        self.expressViewHeightConstraint.constant = 0.001;
        self.commentViewHeightConstraint.constant = 0.001;
        if (self.listModel.isBusiness) {
            self.statusBtn.hidden = NO;
            self.statusBtn.tag = ActionTypeSellerSend;
            [self.statusBtn setTitle:@"发货" forState:UIControlStateNormal];
        }else{
            self.statusBtn.hidden = YES;
        }
        
        self.sureBtn.hidden = YES;
    }else if (self.model.status == SingleTypeStatusAlreadySend){
        self.singleStatusLab.text = @"已发货";
        if (self.listModel.isBusiness) {
            self.statusBtn.hidden = YES;
        }else{
            [self.statusBtn setTitle:@"确认收货" forState:UIControlStateNormal];
        }
        if (self.model.isUserselfPick) {
            self.expressViewHeightConstraint.constant = 0.01;
        }
        self.commentViewHeightConstraint.constant = 0.001;
        self.sureBtn.hidden = YES;
        self.statusBtn.tag = ActionTypeSureReceive;
    }else if (self.model.status == SingleTypeStatusSureReceive){
        self.singleStatusLab.text = @"已收货";
        [self.statusBtn setTitle:@"退换货" forState:UIControlStateNormal];
        self.statusBtn.tag = ActionTypeApplyBack;
        if (self.listModel.isBusiness) {
            self.statusBtn.hidden = YES;
            [self sellerHideCommentAction];
        }
    }else if (self.model.status == SingleTypeStatusApplyBack){//没有按钮高度
        self.singleStatusLab.text = @"已申请退货";
        self.statusBtn.hidden = YES;
        if (self.listModel.isBusiness) {
            self.statusBtn.hidden = NO;
            [self.statusBtn setTitle:@"同意/拒绝" forState:UIControlStateNormal];
            self.statusBtn.tag = ActionTypeSellerAgree;
            [self sellerHideCommentAction];
        }
    }else if (self.model.status == SingleTypeStatusAgreeBack){
        self.singleStatusLab.text = @"已同意退货";
        [self.statusBtn setTitle:@"退货" forState:UIControlStateNormal];
        self.statusBtn.tag = ActionTypeSendBack;
        if (self.listModel.isBusiness) {
            self.statusBtn.hidden = YES;
            self.statusBtn.tag = ActionTypeSellerAgree;
            [self sellerHideCommentAction];
        }
    }else if (self.model.status == SingleTypeStatusBackSend){
        self.singleStatusLab.text = @"退货商品已寄出";
        self.statusBtn.hidden = YES;
        if (self.listModel.isBusiness) {
            self.statusBtn.hidden = NO;
            self.statusBtn.tag = ActionTypeSellerSureReceive;
            [self.statusBtn setTitle:@"确认收货" forState:UIControlStateNormal];
            [self sellerHideCommentAction];
        }
    }else if (self.model.status == SingleTypeStatusReceiveBack){//没有按钮高度
        self.singleStatusLab.text = @"退货商品已验收";
        self.statusBtn.hidden = YES;
        if (self.listModel.isBusiness) {
            self.statusBtn.hidden = NO;
            self.statusBtn.tag = ActionTypeSellerSurePayBack;
            [self.statusBtn setTitle:@"确认打款" forState:UIControlStateNormal];
            [self sellerHideCommentAction];
        }
    }else if (self.model.status == SingleTypeStatusBackSuccess){//没有按钮高度
        self.singleStatusLab.text = @"退货成功";
        self.statusBtn.hidden = YES;
        if (self.listModel.isBusiness) {
            [self sellerHideCommentAction];
        }
    }if (self.model.status == SingleTypeStatusRefuseApplyBack){
        self.singleStatusLab.text = @"商家拒绝退货申请";
        [self.statusBtn setTitle:@"退换货" forState:UIControlStateNormal];
        self.statusBtn.tag = ActionTypeApplyBack;
        if (self.listModel.isBusiness) {
            self.statusBtn.hidden = YES;
            self.statusBtn.tag = ActionTypeSellerAgree;
            [self sellerHideCommentAction];
        }
    }
    if (!(self.model.status == SingleTypeStatusUnpay)&&!(self.model.status == SingleTypeStatusAlreadyPay)) {
        self.expressLab.text = self.model.expressCompany;
        self.expressNumLab.text = self.model.courierNumber;
    }
    if (self.model.isComment) {
        self.slider.userInteractionEnabled = NO;
        self.commentTextView.userInteractionEnabled = NO;
        self.sureBtn.hidden = YES;
        self.commentTextView.text = @"";
        self.slider.value = self.model.commentStartLevel;
        self.commentTextView.text = self.model.commentContent;
        self.sureBtn.hidden = YES;
    }else if (self.listModel.isBusiness){
        self.commentTextView.placeHolder = @"用户暂未评论";
    }
    if (self.model.productType == 2&&self.model.status == SingleTypeStatusSureReceive) {
        self.statusBtn.hidden = YES;
    }
}
//商家禁用评论操作
- (void)sellerHideCommentAction
{
    self.sureBtn.hidden = YES;
    self.commentView.userInteractionEnabled = NO;
}
- (IBAction)payClick:(UIButton *)btn
{
    __WEAK
    if (btn.tag == ActionTypeToPay) {
        [[SingleActionTool shareTool] singleToPayWithModel:self.model success:^(SingleCreateModel *model) {
            SZLSinglePayViewController *payVc = [[SZLSinglePayViewController alloc]init];
            payVc.model = model;
            payVc.payChargeType = PayChargeTypeSingle;
            payVc.paySuccessBlock = ^(){
                weakSelf.statusBtn.hidden = YES;
                weakSelf.singleStatusLab.text = @"待发货";
                if (weakSelf.statueChangeBlock) {
                    weakSelf.listModel.status = SingleTypeStatusAlreadyPay;//改变列表页的模型状态
                    weakSelf.statueChangeBlock(weakSelf.listModel);
                }
            };
            [weakSelf.navigationController pushViewController:payVc animated:YES];
        }];
    }else if (btn.tag == ActionTypeSureReceive){
        [[SingleActionTool shareTool] sureReceive:self.model success:^{
            [MBProgressHUD showSuccess:@"收货成功" toView:self.view];
            weakSelf.singleStatusLab.text = @"已收货";
            [weakSelf.statusBtn setTitle:@"退换货" forState:UIControlStateNormal];
            self.statusBtn.tag = ActionTypeApplyBack;
            weakSelf.commentViewHeightConstraint.constant = 140;
            weakSelf.sureBtn.hidden = NO;
            if (weakSelf.statueChangeBlock) {
                weakSelf.listModel.status = SingleTypeStatusSureReceive;//改变列表页的模型状态
                weakSelf.statueChangeBlock(weakSelf.listModel);
            }
            if (self.model.productType == 2) {
                self.statusBtn.hidden = YES;
            }
        }];
    }else if (btn.tag == ActionTypeApplyBack){
        [[SingleActionTool shareTool] backApply:self.model success:^{
            [MBProgressHUD showSuccess:@"已发送退货申请" toView:self.view];
            self.statusBtn.hidden = YES;
            self.singleStatusLab.text = @"已申请退货";
            if (weakSelf.statueChangeBlock) {
                weakSelf.listModel.status = SingleTypeStatusApplyBack;//改变列表页的模型状态
                weakSelf.statueChangeBlock(weakSelf.listModel);
            }
        }];
    }else if (btn.tag == ActionTypeSendBack){
        [[SingleActionTool shareTool] sendBack:self.model type:NO success:^{
            [MBProgressHUD showSuccess:@"已提交快递信息" toView:self.view];
            weakSelf.statusBtn.hidden = YES;
            weakSelf.singleStatusLab.text = @"退货商品已寄出";
            if (weakSelf.statueChangeBlock) {
                weakSelf.listModel.status = SingleTypeStatusBackSend;//改变列表页的模型状态
                weakSelf.statueChangeBlock(weakSelf.listModel);
            }
        }];
    }else if (btn.tag == ActionTypeSellerSend){
        [[SingleActionTool shareTool] sellerSendGoods:self.model success:^{
            [MBProgressHUD showSuccess:@"发货成功" toView:self.view];
            weakSelf.statusBtn.hidden = YES;
            weakSelf.singleStatusLab.text = @"已发货";
            if (weakSelf.statueChangeBlock) {
                weakSelf.statueChangeBlock(nil);//传空回去重新请求
            }
        }];
    }else if (btn.tag == ActionTypeSellerAgree){
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"是否同意退货" message:nil delegate:self cancelButtonTitle:@"拒绝" otherButtonTitles:@"同意", nil];
        [alert show];
        [alert handlerClickedButton:^(UIAlertView *alertView, NSInteger btnIndex) {
            if (btnIndex == 0) {
                [[SingleActionTool shareTool] sellerAgreeRefuse:self.model type:10 success:^{
                    [MBProgressHUD showSuccess:@"已拒绝退货" toView:self.view];
                    weakSelf.singleStatusLab.text = @"已拒绝退货";
                    self.statusBtn.hidden = YES;
                    if (weakSelf.statueChangeBlock) {
                        weakSelf.listModel.status = SingleTypeStatusRefuseApplyBack;//改变列表页的模型状态
                        weakSelf.statueChangeBlock(weakSelf.listModel);
                    }
                }];
            }else{
                [[SingleActionTool shareTool] sellerAgreeRefuse:self.model type:6 success:^{
                    [MBProgressHUD showSuccess:@"已同意退货" toView:self.view];
                    weakSelf.singleStatusLab.text = @"已同意退货";
                    self.statusBtn.hidden = YES;
                    if (weakSelf.statueChangeBlock) {
                        weakSelf.listModel.status = SingleTypeStatusAgreeBack;//改变列表页的模型状态
                        weakSelf.statueChangeBlock(weakSelf.listModel);
                    }
                }];
            }
        }];
    }else if (btn.tag == ActionTypeSellerSureReceive){
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"确认已收货吗" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
        [alert show];
        [alert handlerClickedButton:^(UIAlertView *alertView, NSInteger btnIndex) {
            [[SingleActionTool shareTool] sellerSureReturn:self.model success:^{
                [MBProgressHUD showSuccess:@"确认收货成功" toView:self.view];
                if (self.model.tradeChannel == 4) {
                    weakSelf.statusBtn.hidden = YES;
                    weakSelf.singleStatusLab.text = @"退货成功";
                    if (weakSelf.statueChangeBlock) {
                        weakSelf.listModel.status = SingleTypeStatusBackSuccess;//改变列表页的模型状态
                        weakSelf.statueChangeBlock(weakSelf.listModel);
                    }
                }else{
                    weakSelf.statusBtn.hidden = NO;
                    weakSelf.singleStatusLab.text = @"收货成功";
                    [weakSelf.statusBtn setTitle:@"确认打款" forState:UIControlStateNormal];
                    weakSelf.statusBtn.tag = ActionTypeSellerSurePayBack;
                    if (weakSelf.statueChangeBlock) {
                        weakSelf.listModel.status = SingleTypeStatusReceiveBack;//改变列表页的模型状态
                        weakSelf.statueChangeBlock(weakSelf.listModel);
                    }
                }
            }];
        }];
    }else if (btn.tag == ActionTypeSellerSurePayBack){//商家确认打款
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"确认已打款吗" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
        [alert show];
        [alert handlerClickedButton:^(UIAlertView *alertView, NSInteger btnIndex) {
            [[SingleActionTool shareTool] sellerReturnMoney:self.model success:^{
                [MBProgressHUD showSuccess:@"已打款" toView:self.view];
                weakSelf.statusBtn.hidden = YES;
                weakSelf.singleStatusLab.text = @"退货成功";
                if (weakSelf.statueChangeBlock) {
                    weakSelf.listModel.status = SingleTypeStatusBackSuccess;//改变列表页的模型状态
                    weakSelf.statueChangeBlock(weakSelf.listModel);
                }
            }];
        }];
    }
}
//订单详情
- (void)getSingleDetail
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    parame[@"orderNo"] = self.listModel.orderNo;
    [self showWaiter];
    [SingleListNetWork singleDetailWithParame:parame response:^(BOOL success, NSString *msg, SingleListModel *model) {
        [self hideWaiter];
        if (success) {
            self.model = model;
            [self setValue];
        }else{
            [MBProgressHUD showError:msg toView:self.view];
        }
    }];
}
//订单评价
- (void)commitContent
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    parame[@"orderNo"] = self.listModel.orderNo;
    parame[@"startLevel"] = @(self.starCount);
    parame[@"content"] = self.commentTextView.text;
    [self showWaiter];
    [SingleListNetWork singleCommentWithParame:parame response:^(BOOL success, NSString *msg) {
        [self hideWaiter];
        if (success) {
            [MBProgressHUD showSuccess:@"评价成功" toView:self.view];
            [self.view endEditing:YES];
            self.slider.userInteractionEnabled = NO;
            self.sureBtn.hidden = YES;
            self.scrollViewBottomConstraint.constant = 0;
            self.containViewHeightConstraint.constant = self.originHeight-(ScreenH-64);
        }else{
            [MBProgressHUD showError:msg toView:self.view];
        }
    }];
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    isTextView = YES;
    return YES;
}
- (void)keyBoardFrameChanged:(NSNotification *)noti
{
    if (!isTextView) return;
    CGRect endRect = [noti.userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    if (endRect.origin.y<ScreenH) {//弹出
        self.scrollViewBottomConstraint.constant = endRect.size.height;
        self.containViewHeightConstraint.constant = self.originHeight-(ScreenH-64-endRect.size.height);
        isTextView = NO;//键盘弹回的时候取消标记
    }else{//关闭
        self.scrollViewBottomConstraint.constant = 0;
        self.containViewHeightConstraint.constant = self.originHeight-(ScreenH-64);
    }
    isAnimate = YES;//标记view是否正在动画
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
        self.scrollview.contentOffset = CGPointMake(0, self.originHeight-self.scrollview.height);
    } completion:^(BOOL finished) {
        isAnimate = NO;
    }];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (isAnimate)return;
    [self.view endEditing:YES];
}

- (void)addObserve
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardFrameChanged:) name:UIKeyboardDidChangeFrameNotification object:nil];
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardDidChangeFrameNotification object:nil];
}

@end
